import hashlib
import json
from time import time
from urllib.parse import urlparse
import requests


class BlockChain:

    def __init__(self):
        self.chain = []  # 储存区块链
        self.current_transactions = []  # 储存当前交易
        self.nodes = set()  # 储存所有节点

        # 创建创世块
        self.new_block(previous_hash='1', proof=100)

    # 生成新区块
    def new_block(self, proof, previous_hash=None):
        """生成新块"""
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1])
        }
        # 重置当前交易区块
        self.current_transactions = []
        # 添加新区块
        self.chain.append(block)
        return block

    # 生成新交易信息，信息将加入到下一个待挖的区块中
    def new_transaction(self, sender, recipient, amount):
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount
        })
        return self.last_block['index'] + 1

    # 对区块的hash加密
    @staticmethod
    def hash(block):
        """生成区块的SHA-256 hash值"""
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    # 获取放最新的那个区块
    @property
    def last_block(self):
        return self.chain[-1]

    # 简易实现pow算法
    def proof_of_work(self, last_proof):
        """
        简单的工作量证明
        查找一个P'使得hash(pp')以4个0开头
        p是上一个区块的证明，p'是当前的证明
        """
        proof = 0
        while self.valid_proof(last_proof, proof) is False:
            proof += 1
        return proof

    # 验证工作证明是否正确
    @staticmethod
    def valid_proof(last_proof, proof):
        """验证证明：是否hash(last_proof,proof)以4个0 开头"""
        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == '0000'

    # 添加(注册)一个新的节点
    def register_node(self, address):
        parsed_url = urlparse(address)
        self.nodes.add(parsed_url.netloc)

    # 简易实现共识算法
    def resolve_conflicts(self):
        """
        冲突是指不同的节点拥有不同的链，为了解决这个问题，规定最长的，
        有效的链才是最终的链。网络中有效最长链才是实际的链。
        """
        neighbours = self.nodes  # 网络中所有的节点
        new_chain = None
        max_length = len(self.chain)
        # 遍历所有的节点
        for node in neighbours:
            response = requests.get(f'http://{node}/chain')
            if response.status_code == 200:
                length = response.json()['length']
                chain = response.json()['chain']
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain
        # 如果发现有效更长链，就替换掉自己的链
        if new_chain:
            self.chain = new_chain
            return True

        return False

    # 验证区块链是否是有效区块链
    def valid_chain(self, chain):
        """遍历每个块，验证hash和proof"""
        last_block = chain[0]  # 第一个区块
        current_index = 1
        while current_index < len(chain):
            block = chain[current_index]

            # 1.验证当前区块的previous_hash是否和上一个区块的hash相等
            if block['previous_hash'] != self.hash(last_block):
                return False
            # 2.验证工作量证明
            if not self.valid_proof(last_block['proof'], block['proof']):
                return False

            last_block = block
            current_index += 1

        return True

